<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="备件编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入备件编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入备件名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="有无计划" prop="hasPlan">
        <el-select v-model="queryParams.hasPlan" placeholder="全部" clearable>
          <el-option :value="1" label="有计划"></el-option>
          <el-option :value="0" label="无计划"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <SpareFormDialog
      v-model:visible="dlgVisible"
      :mode="dlgMode"
      :model="dlgModel"
      :submitting="dlgLoading"
      @submit="onDlgSubmit"
    />

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sbtz:spare:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sbtz:spare:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sbtz:spare:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sbtz:spare:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="spareList"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />

      <!-- 分组：基本信息 -->
      <el-table-column
        label="基本信息"
        align="center"
        header-class-name="group-basic-header"
      >
        <el-table-column
          label="备件编码"
          prop="code"
          min-width="140"
          class-name="group-basic-body"
        />
        <el-table-column
          label="备件名称"
          prop="name"
          min-width="180"
          class-name="group-basic-body"
        />
        <el-table-column
          label="类型"
          prop="type"
          width="100"
          class-name="group-basic-body"
        >
          <template #default="{ row }">
            <el-tag
              size="small"
              :type="(row.type ?? 0) === 1 ? 'warning' : 'success'"
            >
              {{ (row.type ?? 0) === 1 ? "特殊" : "普通" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="状态"
          prop="status"
          width="90"
          class-name="group-basic-body"
        >
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'info'" size="small">
              {{ row.status === 0 ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 分组：库存信息 -->
      <el-table-column
        label="库存信息"
        align="center"
        header-class-name="group-stock-header"
      >
        <el-table-column
          label="最低库存"
          prop="minStock"
          width="110"
          align="center"
          class-name="group-stock-body"
        />
        <el-table-column
          label="最高库存"
          prop="maxStock"
          width="110"
          align="center"
          class-name="group-stock-body"
        />
        <el-table-column
          label="总库存"
          prop="stockTotal"
          width="110"
          align="center"
          class-name="group-stock-body"
        />
        <el-table-column
          label="当前库存"
          prop="stockAvailable"
          width="110"
          align="center"
          class-name="group-stock-body"
        />
        <el-table-column
          label="已用数量"
          width="110"
          align="center"
          class-name="group-stock-body"
        >
          <template #default="{ row }">
            {{ usedCount(row) }}
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 分组：时间（保持默认风格） -->
      <!-- <el-table-column label="时间" align="center">
        <el-table-column label="计划日期" prop="planDate" width="120" />
        <el-table-column label="采购周期(天)" prop="orderDate" width="120" />
      </el-table-column> -->

      <!-- 计划信息（最近一条 + Popover 展开全部） -->
      <!-- 分组：计划信息（与前面两组同风格） -->
      <el-table-column
        label="计划信息"
        header-align="center"
        align="center"
        header-class-name="group-plan-header"
      >
        <!-- 计划日期 -->
        <el-table-column
          label="计划日期"
          width="120"
          align="center"
          class-name="group-plan-body"
        >
          <template #default="scope">
            <div
              v-if="
                Array.isArray(scope.row.planInfos) && scope.row.planInfos.length
              "
              class="stack num-col"
            >
              <div
                v-for="(p, i) in scope.row.planInfos"
                :key="p.planId ?? i"
                class="line"
              >
                {{ fmtDate(p.planDate) }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 所需数量 -->
        <el-table-column
          label="所需数量"
          width="100"
          align="center"
          class-name="group-plan-body"
        >
          <template #default="scope">
            <div
              v-if="
                Array.isArray(scope.row.planInfos) && scope.row.planInfos.length
              "
              class="stack num-col"
            >
              <div
                v-for="(p, i) in scope.row.planInfos"
                :key="p.planId ?? i"
                class="line"
              >
                {{ p.qty ?? "-" }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 采购周期(天) -->
        <el-table-column
          label="采购周期(天)"
          width="120"
          align="center"
          class-name="group-plan-body"
        >
          <template #default="scope">
            <div
              v-if="
                Array.isArray(scope.row.planInfos) && scope.row.planInfos.length
              "
              class="stack num-col"
            >
              <div
                v-for="(p, i) in scope.row.planInfos"
                :key="p.planId ?? i"
                class="line"
              >
                {{ p.orderDate ?? "-" }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 设备名称 -->
        <el-table-column
          label="设备名称"
          min-width="160"
          align="left"
          class-name="group-plan-body"
        >
          <template #default="scope">
            <div
              v-if="
                Array.isArray(scope.row.planInfos) && scope.row.planInfos.length
              "
              class="stack"
            >
              <div
                v-for="(p, i) in scope.row.planInfos"
                :key="p.planId ?? i"
                class="line one-line"
              >
                <el-tooltip :content="p.assetName || '-'" placement="top">
                  <span>{{ p.assetName || "-" }}</span>
                </el-tooltip>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 计划标题 -->
        <el-table-column
          label="计划标题"
          min-width="180"
          align="left"
          class-name="group-plan-body"
        >
          <template #default="scope">
            <div
              v-if="
                Array.isArray(scope.row.planInfos) && scope.row.planInfos.length
              "
              class="stack"
            >
              <div
                v-for="(p, i) in scope.row.planInfos"
                :key="p.planId ?? i"
                class="line one-line"
              >
                <el-tooltip :content="p.planTitle || '-'" placement="top">
                  <span>{{ p.planTitle || "-" }}</span>
                </el-tooltip>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 规格/厂商（多行渲染） -->
      <el-table-column label="厂商 / 规格" min-width="260">
        <template #default="{ row }">
          <div v-if="row.variants?.length" class="variants">
            <div class="variant-line" v-for="(v, i) in row.variants" :key="i">
              <el-tag size="small">{{ v.vendor || "-" }}</el-tag>
              <span class="sep">/</span>
              <el-tag size="small" type="info">{{ v.spec || "-" }}</el-tag>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sbtz:spare:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sbtz:spare:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改备件库存对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="spareRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="备件编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入备件编码" />
        </el-form-item>
        <el-form-item label="备件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入备件名称" />
        </el-form-item>
        <el-form-item label="总库存" prop="stockTotal">
          <el-input v-model="form.stockTotal" placeholder="请输入总库存" />
        </el-form-item>
        <el-form-item label="在线库存" prop="stockAvailable">
          <el-input
            v-model="form.stockAvailable"
            placeholder="请输入在线库存"
          />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Spare">
import {
  listSpare,
  getSpare,
  delSpare,
  addSpare,
  updateSpare,
  addSpareBatch,
} from "@/api/sbtz/spare";
import SpareBatchEditor from "@/components/sbtz/spare/SpareBatchEditor.vue";
import SpareFormDialog from "@/components/sbtz/spare/SpareFormDialog.vue";

const { proxy } = getCurrentInstance();

const spareList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const batchOpen = ref(false);
const batchSubmitting = ref(false);

const dlgVisible = ref(false);
const dlgMode = ref("add"); // 'add' | 'edit'
const dlgLoading = ref(false);
const dlgModel = ref({});

function openBatch() {
  batchOpen.value = true;
}

async function onBatchSubmit(payload) {
  try {
    batchSubmitting.value = true;
    await addSpareBatch(payload);
    proxy.$modal.msgSuccess("导入成功");
    batchOpen.value = false;
  } catch (e) {
    proxy.$modal.msgError(e?.msg || e?.message || "导入失败");
  } finally {
    batchSubmitting.value = false;
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    stockTotal: null,
    stockAvailable: null,
    status: null,
    remark: null,
    hasPlan: null,
  },
  rules: {
    code: [{ required: true, message: "备件编码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "备件名称不能为空", trigger: "blur" }], 
    stockTotal: [
      { required: true, message: "总库存不能为空", trigger: "blur" },
    ],
    stockAvailable: [
      { required: true, message: "在线库存不能为空", trigger: "blur" },
    ],
    status: [
      { required: true, message: "使用状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

function usedCount(row) {
  const t = Number(row.stockTotal || 0);
  const a = Number(row.stockAvailable || 0);
  return t - a;
}

function getList() {
  loading.value = true;
  listSpare(queryParams.value)
    .then((res) => {
      // ① rows 兜底
      const rawList = res?.rows ?? res?.data?.rows ?? res?.data ?? [];

      // ② 逐条归一化 planInfos（兼容各种命名：planInfos/plan_infos/planInfo）
      spareList.value = rawList.map((r) => {
        const srcPlanInfos = r?.planInfos ?? r?.plan_infos ?? r?.planInfo ?? [];

        // ③ 子项字段也做驼峰归一化（兼容 plan_date / order_date / asset_name / plan_title / plan_id）
        const planInfos = (Array.isArray(srcPlanInfos) ? srcPlanInfos : []).map(
          (p) => ({
            planId: p.planId ?? p.plan_id ?? null,
            planDate: p.planDate ?? p.plan_date ?? null,
            orderDate: p.orderDate ?? p.order_date ?? null,
            qty: p.qty ?? null,
            assetName: p.assetName ?? p.asset_name ?? null,
            planTitle: p.planTitle ?? p.plan_title ?? null,
          })
        );

        // ④ 统一按“计划日期”倒序
        planInfos.sort(
          (a, b) => new Date(b.planDate || 0) - new Date(a.planDate || 0)
        );

        return {
          ...r,
          planInfos,
          variants: r.variants || [],
        };
      });

      // ⑤ total 兜底
      total.value = res?.total ?? res?.data?.total ?? spareList.value.length;
      loading.value = false;

      // ★ 若还不显示，临时看看首条数据结构
      // console.log('spareList[0] =>', spareList.value[0])
    })
    .catch(() => {
      loading.value = false;
    });
}

function fmtDate(d) {
  if (!d) return "-";
  if (typeof d === "string") return d;
  try {
    const dt = new Date(d);
    const y = dt.getFullYear();
    const m = String(dt.getMonth() + 1).padStart(2, "0");
    const day = String(dt.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  } catch {
    return "-";
  }
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    id: null,
    code: null,
    name: null,
    spec: null,
    unit: null,
    stockTotal: null,
    stockAvailable: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    hasPlan: null,
  };
  proxy.resetForm("spareRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  dlgMode.value = "add";
  dlgModel.value = {
    unit: "个",
    status: 0,
    type: 0,
    stockTotal: 0,
    stockAvailable: 0,
    variants: [],
  };
  dlgVisible.value = true;
}

async function handleUpdate(row) {
  const id = row.id || ids.value?.[0];
  if (!id) return;

  dlgMode.value = "edit";
  dlgLoading.value = true;
  try {
    const res = await getSpare(id);
    dlgModel.value = res.data || {};
    dlgVisible.value = true;
  } finally {
    dlgLoading.value = false;
  }
}

async function onDlgSubmit(payload) {
  dlgLoading.value = true;
  try {
    if (dlgMode.value === "add") {
      await addSpare(payload);
      proxy.$modal.msgSuccess("新增成功");
    } else {
      await updateSpare(payload);
      proxy.$modal.msgSuccess("修改成功");
    }
    dlgVisible.value = false;
    getList();
  } finally {
    dlgLoading.value = false;
  }
}

function submitForm() {
  proxy.$refs["spareRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateSpare(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSpare(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除备件库存编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delSpare(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleExport() {
  proxy.download(
    "sbtz/spare/export",
    {
      ...queryParams.value,
    },
    `spare_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 容器间距 */
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 12px;
}

/* —— 表格基础 —— */
:deep(.el-table) {
  font-size: 13px;
  --el-table-border-color: #ebeef5;
}
:deep(.el-table .el-table__row:hover) {
  background-color: transparent; /* 用分组自定义 hover，而不是统一淡蓝 */
}
:deep(.el-table th) {
  background-color: #f8f9fb;
  font-weight: 600;
}

/* —— 分组：基本信息 —— */
/* 组头 */
:deep(.group-basic-header) {
  background-color: #eaf4ff !important;
  color: #0d3b66 !important;
  font-weight: 700;
  border-bottom: 2px solid #dce4f2 !important;
}
/* 组内单元格背景（叶子列 td 会带上 class-name） */
:deep(td.group-basic-body) {
  background-color: #f5faff !important;
}
/* hover 时保持分组色并略微加深 */
:deep(.el-table__body tr:hover > td.group-basic-body) {
  background-color: #eef6ff !important;
}

/* —— 分组：库存信息 —— */
:deep(.group-stock-header) {
  background-color: #e8f9f0 !important;
  color: #1d643b !important;
  font-weight: 700;
  border-bottom: 2px solid #dcefe6 !important;
}
:deep(td.group-stock-body) {
  background-color: #f6fff8 !important;
}
:deep(.el-table__body tr:hover > td.group-stock-body) {
  background-color: #e9fcef !important;
}

/* 标签优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-size: 12px;
  padding: 0 6px;
}

/* 规格/厂商布局 */
.variants {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 8px;
}
.variant-line {
  display: flex;
  align-items: center;
  gap: 4px;
}
.sep {
  color: #bbb;
}

/* 工具栏右对齐（如果需要） */
.right-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* —— 分组：计划信息 —— */
/* 单元格里纵向堆叠子行 */
/* —— 分组：计划信息 —— */
:deep(.group-plan-header) {
  background-color: #f4ecff !important; /* 组头底色 */
  color: #5b3aa4 !important; /* 组头文字色 */
  font-weight: 700;
  border-bottom: 2px solid #e6dcff !important;
}
:deep(td.group-plan-body) {
  background-color: #faf7ff !important; /* 叶子列底色 */
}
:deep(.el-table__body tr:hover > td.group-plan-body) {
  background-color: #f1eaff !important; /* hover 时加深一点 */
}
</style>
